import PyPDF2
from PyPDF2 import PdfReader, PdfWriter
from PyPDF2.generic import ArrayObject
from PIL import Image
import fitz
import io
import webview

window = None

def select_and_process_file(e):
    file_types = ('PDF (*.pdf)',)

    result = window.create_file_dialog(
        webview.OPEN_DIALOG, allow_multiple=False, file_types=file_types
    )
    if result:
        window.evaluate_js(f'document.getElementById("p").innerText = "开始处理, 请等待.";')
        # 获取选择的文件路径
        filepath = result[0]
        new_pdf_filepath = reset_pdf(filepath)
        
        window.evaluate_js(f'document.getElementById("p").innerText = "处理完了, 在原文件位置生成了新文件, 也就是:{new_pdf_filepath}";')


def reset_pdf(filepath):
    old_pdf = fitz.open(filepath)
    new_pdf = fitz.open()
    for page_num, page in enumerate(old_pdf):
        pix = page.get_pixmap()
        pix.save("temp.png")
        img = fitz.open("temp.png") 
        rect = img[0].rect  # pic dimension
        pdfbytes = img.convert_to_pdf()  # make a PDF stream
        img.close()  # no longer needed
        imgPDF = fitz.open("pdf", pdfbytes)  # open stream as PDF
        page = new_pdf.new_page(width = rect.width,  # new page with ...
                       height = rect.height)  # pic dimension
        page.show_pdf_page(rect, imgPDF, 0)  # image fills the page
        
    new_pdf_filepath = filepath.split(".pdf")[0]+"_nopasswd.pdf"
    new_pdf.save(new_pdf_filepath)  # 保存 PDF 文件 
    return new_pdf_filepath

def bind(window):
    button = window.dom.get_element('#button')
    button.events.click += select_and_process_file

if __name__ == '__main__':
    # reset_pdf('腾云S5000C高性能通用微处理器软件编程手册-V0.6.pdf')
    window = webview.create_window("处理编辑加密的pdf文件", html="<button id='button'>选择文件</button><br><p id='p'>本工具用于读取一个pdf, 然后逐像素重建这个pdf, 请注意! 有些编辑加密的pdf, 受版权保护, 严禁使用本工具处理版权保护的pdf!</p>")
    webview.start(bind, window)